package com.adnauseum;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.*;
import android.widget.*;

import java.util.ArrayList;
import java.util.HashMap;

public class ScoreScreen extends Activity {
    private int lifeTotal = 20;
    private int fontSize = 70;
    private int playerWidth;
    private int SCORE_SCREEN_MENU = 0;
    private int ADD_PLAYER = 0;
    private int REMOVE_PLAYER = 1;
    private int RESET = 2;
    private LinearLayout mainLayout;
    private gameModes currentGameMode;

    private enum gameModes {ONE, EDH, THG}
    private ArrayList<Object> playerOrder;
    private HashMap<Object, Integer> players;
    private HashMap<Object, View> playerLayouts;

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        super.onCreateOptionsMenu(menu);

        menu.add(SCORE_SCREEN_MENU, ADD_PLAYER, 0, "Add Player").setIcon(android.R.drawable.ic_input_add);
        menu.add(SCORE_SCREEN_MENU, REMOVE_PLAYER, 0, "Remove Player").setIcon(android.R.drawable.ic_delete);
        menu.add(SCORE_SCREEN_MENU, RESET, 0, "Reset").setIcon(android.R.drawable.ic_menu_revert);

        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        if (item.getItemId() == ADD_PLAYER) {
            addPlayer();
            return true;
        } else if (item.getItemId() == REMOVE_PLAYER) {
            removePlayer();
        } else if (item.getItemId() == RESET) {
            initialize();
        }

        return false;
    }

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        //todo: allow the user to set the game mode on startup via a popup, here
        currentGameMode = gameModes.ONE;
        initialize();

        Log.d(this.getClass().toString(), "Exiting OnCreate()");
    }
    
    private void initialize() {
        //todo: ensure all context sensitive data gets wiped when this gets called.
        HorizontalScrollView hsv = new HorizontalScrollView(this);
        mainLayout = new LinearLayout(this);
        playerLayouts = new HashMap<Object, View>();
        playerOrder = new ArrayList<Object>();
        players = new HashMap<Object, Integer>();

        int windowWidth = getWindow().getWindowManager().getDefaultDisplay().getWidth();
        playerWidth = (windowWidth - 4) / 2;

        switch (currentGameMode){
            case EDH:
                lifeTotal = 40;
                fontSize = 50;
                break;
            case THG:
                lifeTotal = 30;
                fontSize = 50;
                break;
        }

        addPlayer();
        addPlayer();

        mainLayout.setBackgroundColor(getResources().getColor(R.color.black));
        mainLayout.setVerticalFadingEdgeEnabled(true);

        hsv.addView(mainLayout, new HorizontalScrollView.LayoutParams(
                HorizontalScrollView.LayoutParams.FILL_PARENT, HorizontalScrollView.LayoutParams.FILL_PARENT));
        hsv.setVerticalFadingEdgeEnabled(false);

        setContentView(hsv);
        Log.d(this.getClass().toString(), "Exiting Initialize()");
    }

    private RelativeLayout addPlayer() {
        RelativeLayout layout = new RelativeLayout(this);
        layout.setId(layout.hashCode());
        layout.setBackgroundColor(getResources().getColor(R.color.black));
        Context context = getApplicationContext();

        int wrap = RelativeLayout.LayoutParams.WRAP_CONTENT;
        RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(playerWidth, wrap);

        TextView player = new TextView(context);
        player.setId(player.hashCode());
        players.put(player.getId(), new Integer(lifeTotal));
        playerOrder.add(player.getId());
        player.setText(String.valueOf(lifeTotal));
        player.setTextSize(fontSize);
        player.setBackgroundColor(getResources().getColor(R.color.dark_red));
        player.setGravity(Gravity.CENTER_HORIZONTAL);
        lp.addRule(RelativeLayout.ALIGN_TOP, layout.getId());
        layout.addView(player, lp);

        View horizontalSpacer = new View(getApplicationContext());
        horizontalSpacer.setId(horizontalSpacer.hashCode());
        horizontalSpacer.setBackgroundColor(getResources().getColor(R.color.black));
        lp = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, 2);
        lp.addRule(RelativeLayout.BELOW, player.getId());
        layout.addView(horizontalSpacer, lp);

        RelativeLayout buttonView = new RelativeLayout(getApplicationContext());
        buttonView.setBackgroundColor(getResources().getColor(R.color.dark_gray));
        buttonView.setId(buttonView.hashCode());
        
        lp = new RelativeLayout.LayoutParams(playerWidth / 2, wrap);
        lp.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM, buttonView.getId());
        Button minusOne = createButton("-1", getResources().getColor(R.color.red), lp, buttonView, player.getId() );

        lp = new RelativeLayout.LayoutParams(playerWidth / 2, wrap);
        lp.addRule(RelativeLayout.RIGHT_OF, minusOne.getId());
        lp.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM, buttonView.getId());
        Button minusFive = createButton("-5", getResources().getColor(R.color.red), lp, buttonView, player.getId() );

        lp = new RelativeLayout.LayoutParams(playerWidth / 2, wrap);
        lp.addRule(RelativeLayout.ABOVE, minusOne.getId());
        Button plusOne = createButton("+1", getResources().getColor(R.color.green), lp, buttonView, player.getId() );

        lp = new RelativeLayout.LayoutParams(playerWidth / 2, wrap);
        lp.addRule(RelativeLayout.ABOVE, minusFive.getId());
        lp.addRule(RelativeLayout.RIGHT_OF, plusOne.getId());
        Button plusFive = createButton("+5", getResources().getColor(R.color.green), lp, buttonView, player.getId() );

        View spacer = new View(getApplicationContext());
        spacer.setBackgroundColor(getResources().getColor(R.color.black));
        lp = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, 2);
        lp.addRule(RelativeLayout.ALIGN_PARENT_TOP, buttonView.getId());
        buttonView.addView(spacer, lp);
        
        lp = new RelativeLayout.LayoutParams(playerWidth, 103);
        lp.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM, layout.getId());
        layout.addView(buttonView, lp);

        ScrollView historyScrollView = new ScrollView(getApplicationContext());
        historyScrollView.setBackgroundColor(getResources().getColor(R.color.dark_gray));
        lp = new RelativeLayout.LayoutParams(playerWidth, RelativeLayout.LayoutParams.FILL_PARENT);
        lp.addRule(RelativeLayout.BELOW, horizontalSpacer.getId());
        lp.addRule(RelativeLayout.ABOVE, buttonView.getId());
        layout.addView(historyScrollView, lp);

        TextView startingLife = new TextView(getApplicationContext());
        startingLife.setGravity(Gravity.CENTER);
        startingLife.setId(startingLife.hashCode());
        startingLife.setText(String.valueOf(lifeTotal));

        LinearLayout historyLinear = new LinearLayout(getApplicationContext());
        historyLinear.setOrientation(LinearLayout.VERTICAL);
        historyLinear.addView(startingLife);
        historyScrollView.addView(historyLinear);

        layout.setPadding(1,0,1,0);
        playerLayouts.put(player.getId(), layout);
        player.setContentDescription(String.valueOf(startingLife.getId()));
        mainLayout.addView(layout, new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.FILL_PARENT));
        return layout;
    }

    public void removePlayer() {
        try {
            final PopupWindow popup = new PopupWindow(getApplicationContext());
            LinearLayout entryField = new LinearLayout(getApplicationContext());

            ArrayList<Integer> totals = new ArrayList<Integer>();
            for(Object id : playerOrder){
                totals.add(Integer.parseInt(((TextView)findViewById(Integer.parseInt(id.toString()))).getText().toString()));
            }

            final Spinner spinner = new Spinner(this);
            ArrayAdapter spinnerArrayAdapter = new ArrayAdapter(this, android.R.layout.simple_spinner_dropdown_item, totals);
            spinner.setAdapter(spinnerArrayAdapter);

            Button button = new Button(this);
            button.setBackgroundDrawable(getResources().getDrawable(android.R.drawable.ic_menu_delete));
            button.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    removePlayer(spinner.getSelectedItemPosition());
                    popup.dismiss();
                }
            });

            Button cancelButton = new Button(this);
            cancelButton.setBackgroundDrawable(getResources().getDrawable(android.R.drawable.ic_delete));
            cancelButton.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    popup.dismiss();
                }
            });

            entryField.addView(spinner);
            entryField.addView(button);
            entryField.addView(cancelButton);

            popup.setContentView(entryField);
            popup.showAtLocation(mainLayout, Gravity.CENTER, 10, 10);

            popup.update(0, 0, 230, 55);
        } catch (Exception e) {
            Log.e(this.getClass().toString(), "Error removing player");
        }
    }

    private void removePlayer(int index) {
        Object key = playerOrder.get(index);
        RelativeLayout relativeLayout = (RelativeLayout)playerLayouts.get(key);

        playerLayouts.remove(key);
        playerOrder.remove(key);
        players.remove(key);
        mainLayout.removeView(relativeLayout);
    }

    private Button createButton(String s, int color, RelativeLayout.LayoutParams lp, RelativeLayout layout, Object tag) {
        Button button = null;
        try { 
            button = new Button(getApplicationContext());
            button.setOnClickListener(new ButtonListener());
            button.setId(button.hashCode());
            button.setTag(tag);
            button.setTextColor(color);
            button.setText(s);

            layout.addView(button, lp);
        } catch (Exception e) {
            Log.e(this.getClass().toString(), "Error creating button +/-");
        }
        return button;
    }

    private class ButtonListener implements View.OnClickListener {
        public void onClick(View view) {
            char operation = ((Button)view).getText().charAt(0);
            String amount = ((Button)view).getText().subSequence(1, ((Button) view).getText().length()).toString();
            String tag = view.getTag().toString();
            Integer adjustment = Integer.parseInt(amount);
            int color = getResources().getColor(R.color.green);

            if (operation == '-'){
                color = getResources().getColor(R.color.red);
                adjustment *= -1;
            }

            int id = Integer.parseInt(tag);
            TextView totalTv = (TextView)findViewById(id);

            String tmpId = totalTv.getContentDescription().toString();
            int anchorIndex = Integer.parseInt(tmpId);
            TextView anchorView = (TextView)findViewById(anchorIndex);
            LinearLayout linearLayout = ((LinearLayout)anchorView.getParent());
            final ScrollView scrollView = (ScrollView)linearLayout.getParent();


            RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(
                    ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            TextView history = new TextView(getApplicationContext());
            history.setGravity(Gravity.CENTER);
            history.setId(history.hashCode());
            history.setTextColor(color);
            lp.addRule(RelativeLayout.CENTER_HORIZONTAL);
            lp.addRule(RelativeLayout.BELOW, anchorView.getId());

            int life = players.get(id);
            life += adjustment;
            players.put(id, new Integer(life));
            totalTv.setText(String.valueOf(life));

            history.setText( ((Button)view).getText() + " = " + life );
            linearLayout.addView(history, lp);
            
            scrollView.post(new Runnable() {
                public void run() {
                    scrollView.fullScroll(ScrollView.FOCUS_DOWN);
                }
            });

            totalTv.setContentDescription(String.valueOf(history.getId()));
        }
    }
}